<?php
namespace app\api\controller\robat;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\common\model\customer\Subscribe as SubscribeModel;
use app\common\model\company\Contract as Contractmodel;
use think\Controller;
use think\facade\Cache;
class Subscribe extends Base
{
    public function index()
    {
        //客户预约提醒
        $sb[] = self::customer();
        //8点检查合同信息
        $sendsb = Cache::get('send_contract_reminder');
        if(empty($sendsb)){
            $today = date('H:i',time());
            if($today>='08:00'&&$today<='08:30'){
                //没有发送，且时间在8点-8点10分，直接发送
                $sb[] = self::reminder();
                Cache::set('send_contract_reminder',date('Y-m-d H:i:s',time()));
            }
            
        }
        return $sb;
    }

    //客户预约
    public function customer()
    {
        //预约提醒
        $list = [0, 60, 180];
        $startime = date('Y-m-d H:i', time());
        $endtime  = date('Y-m-d H:i', time() + 60);
        //获取预约信息
        $data = SubscribeModel::where('Status', SubscribeModel::STATEWAIT)->where('SubscribeTime', '>=', $startime)->where('SubscribeTime', '<=', $endtime)->where('IsSend',0)->select();
        //按用户分类
        $user = [];
        foreach ($data as $key => $value) {
            $user[$value['BussinessId']][] = $value;
        }
        //判断每个用户的消息条数
        $rdata = [];
        foreach ($user as $key => $value) {
            $rdata = Sendmessage::Subscribe(['UserId' => $key, 'Count' => count($value)]);
            if($rdata['code']){
                foreach ($value as $key2 => $value2) {
                    $value2->IsSend = 1;
                    $value2->save();
                }
            }
        }
        return sok('客户预约提醒通知完成,已发送'.count($user).'条通知'); 
    }

    /**
     * 合同提醒
     * @return [type] [description]
     */
    public function reminder(){
        $customer = Contractmodel::where('State',Contractmodel::STATEOK);
        //45天提醒
        $data[] = date('Y-m-d',time()+3888000);
        //30天提醒
        $data[] = date('Y-m-d',time()+2592000);
        //15天提醒
        $data[] = date('Y-m-d',time()+1296000);
        //7天提醒
        $data[] = date('Y-m-d',time()+604800);
        //1天提醒
        $data[] = date('Y-m-d',time()+86400);
        //0天提醒
        $data[] = date('Y-m-d',time());
        $customer = $customer->where('EndTime','in',$data);
        $buss = $customer->group('BussinessId')->field(['count(BussinessId) as Count','BussinessId'])->select();
        foreach ($buss as $key => $value) {
            Sendmessage::Contract(6,'',$data);
        }
        return sok('合同提醒系统,已发送'.count($buss).'条通知'); ;
    }

}
